var createError = require('http-errors');
var express = require('express');
var url = require('url')
var path = require('path');
var cookieParser = require('cookie-parser');
var logger = require('morgan');
var session = require('express-session')
var passport = require('passport')
var indexRouter = require('./routes/index');
var storyRouter = require('./routes/story')
var discountRouter = require('./routes/discount');
var usersRouter = require('./routes/users');
var cartRouter = require('./routes/cart');
var register = require('./routes/register');
// var users = require('./routes/users');
// var index = require('./routes/index');
var menu = require('./routes/menu')
var order = require('./routes/order')
var evaluate = require('./routes/evaluateuser')

var mypassport = require('./config/passport')
var news = require('./routes/news')
var join = require('./routes/join')
var cartRouter = require('./routes/cart');

const bodyParser = require("body-parser");
const fs = require("fs");
const config = require("./config.js");
const alipayf2f = require("./lib/alipay_f2f")
var app = express();
//设置跨域请求的允许操作
app.all('*', function (req, res, next) {
  // res.header('Access-Control-Allow-Origin', '*'); //针对所有请求用户都允许
  res.header('Access-Control-Allow-Origin', 'http://localhost:8080'); //针对指定的请求用户允许，其他用户禁止访问
  res.header('Access-Control-Allow-Headers', 'Content-Type,Authorization');
  res.header('Access-Control-Allow-Methods', '*');
  res.header('Access-Control-Allow-Credentials', 'true');
  next()
})

// view engine setup
app.set('views', path.join(__dirname, 'views'));
app.set('view engine', 'jade');

app.use(require("compression")());
app.engine(".ejs", require("ejs").__express);
app.set("views", "./views");
app.set("view engine", "ejs");
app.use(bodyParser.urlencoded({ extended: false }));
app.use(bodyParser.json());

app.use(logger('dev'));
app.use(express.json());
app.use(express.urlencoded({ extended: false }));
app.use(cookieParser());

//加载express-session模块中间件
// app.use(session({
//   secret: 'keyboard cat',
//   resave: true,
//   saveUninitialized: true,
//   cookie: { maxAge: 1000 * 60 * 60 * 2 } //设置session变量的保存时间，从用户最后一次操作网页开始计时
// }))
// // 通用的登录权限验证方法，如果已经通过验证，正常运行，否则跳转到登录页面
// app.use(function(req,res,next){
//   if(path.parse(path.join(__dirname,req.url)).ext=='.js'){
//     next()
//   }
//   //排除几个特殊路由，其他的路由请求按session的逻辑操作
//   else if(req.url == '/login.html' || req.url == '/login' || url.parse(req.url).pathname == '/getVCode'){
//     next()
//   }
//   else if(req.session && req.session.user){
//     next();
//   }else{
//     res.redirect('/login.html') 
//   }
// })
app.use(express.static(path.join(__dirname, 'public')));
app.use(passport.initialize());
mypassport(passport)

app.use((req, res, next) => {
	req.config = config;
	req.alipayf2f = new alipayf2f(config);


	/* 模拟数据库 仅仅作为演示 */
	req.database = {
		get(id) {
			return new Promise((resolve, reject) => {
				if (!fs.existsSync(`./fs-database/${id}.json`)) {
					return resolve(null);
				}
				fs.readFile(`./fs-database/${id}.json`, function (err, data) {
					if (err) return (reject);
					resolve(JSON.parse(data.toString()));
				});
			});
		},

		delete(id) {
			return new Promise((resolve, reject) => {
				if (!fs.existsSync(`./fs-database/${id}.json`)) {
					return resolve();
				}
				fs.unlink((`./fs-database/${id}.json`, function (err) {
					resolve(data);
				}));
			});
		},

		insert(id, obj) {
			return new Promise((resolve, reject) => {
				if (fs.existsSync(`./fs-database/${id}.json`)) {
					return resolve(false);
				}
				fs.writeFile(`./fs-database/${id}.json`, JSON.stringify(obj), function (err) {
					if (err) return reject(err);
					resolve(true);
				});
			});
		},

		update(id, obj) {
			return new Promise((resolve, reject) => {
				fs.writeFile(`./fs-database/${id}.json`, JSON.stringify(obj), function (err) {
					if (err) return reject(err);
					resolve(true);
				});
			});
		},
	};
	res.error = (result) => res.json({ "status": false, message: result });
	res.success = (result) => res.json({ "status": true, message: result });
	res.catch = (error) => {
		console.error(error);
		res.json({ "status": false, "message": "服务器错误, 请稍后重试。" }).end();
	};
	next();
});
app.use("/pay", require("./controllers/pay"));
app.use('/', indexRouter);
app.use('/users', usersRouter);
app.use('/discount',discountRouter);
app.use('/cart',cartRouter);
app.use('/story',storyRouter)
app.use('/register', register);
// app.use('/user', users);
// app.use('/index',index);
app.use('/menu', menu);
app.use('/order', order);
app.use('/evaluate', evaluate);
app.use('/news',news)
app.use('/join',join)
app.use('/cart',cartRouter);
// app.use('/story', users);
// catch 404 and forward to error handler

app.use(function (req, res, next) {
  next(createError(404));
});

// error handler
app.use(function (err, req, res, next) {
  // set locals, only providing error in development
  res.locals.message = err.message;
  res.locals.error = req.app.get('env') === 'development' ? err : {};

  // render the error page
  res.status(err.status || 500);
  res.render('error');
});

module.exports = app;
